<?php
/**
 * Created by PhpStorm.
 * User: Vagrant Archer
 * Date: 2018/1/17
 * Time: 23:13
 */

class BifrostWeOA extends Bifrost
//todo: 将很多中间结果从array变成class
{
    private $monitorGroup;
    private $netLineLatency;
    private $netLineTraffic;

//    public function getAllHost()
//    {
//        $zabbixMethod             =   "host.get";
//        $zabbixParams['output']   =   array("host");
//        $result = $this->zabbixRequest($zabbixMethod, $zabbixParams);
//        var_dump($result);
//
//    }

//    public function getAllHostGroup()
//    {
//        $zabbixMethod             =   "hostgroup.get";
//        $zabbixParams['output']   =   array("name");
//        $result = $this->zabbixRequest($zabbixMethod, $zabbixParams);
//        var_dump($result);
//
//    }

    private function getAllTriggers():array
    {
        $trigger = array();
        $zabbixMethod   =   "Trigger.get";
        $zabbixParam    = '{"output":["triggerid","description","priority","lastchange"],"min_severity":2,"filter":{"value":1},"monitored":true}';
        $zabbixParam = json_decode($zabbixParam, true);
        $zabbixResult = $this->zabbixRequest($zabbixMethod, $zabbixParam);
        foreach ($zabbixResult['result'] as $item) {
            $trigger[] = array(
                        'description'   => $item['description'],
                        'priority'      => $item['priority'],
                        'lastchange'    => $item['lastchange'],
                        'triggerid'     => $item['triggerid'],
                        'hostname'      => $this->getHostNameByTrigger($item['triggerid']),
                );
        }
        return $trigger;
    }

    private function getHostNameByTrigger(string $triggerId):string
    {
        $zabbixMethod   =   "host.get";
        $zabbixParam    = '{"output":["host"],"triggerids":'.$triggerId.'}';
        $zabbixParam = json_decode($zabbixParam, true);
        $zabbixResult = $this->zabbixRequest($zabbixMethod, $zabbixParam);
        return $zabbixResult['result'][0]['host'];
    }


//    private function getGroupName(int $groupNo)
//    {
//
//    }

    private function getGroupTrigger(int $groupNo):string
    {
        $zabbixMethod   =   "Trigger.get";
        $zabbixParam    = '{"output":"extend","groupids":["'.$groupNo.'"],"min_severity":2,"filter":{"value":1},"monitored":true,"countOutput":true}';
        $zabbixParam = json_decode($zabbixParam, true);
        $zabbixResult = $this->zabbixRequest($zabbixMethod, $zabbixParam);

        if (isset($zabbixResult['result'])) {
            return $zabbixResult['result'];
        } else {
            return "N/A";
        }
    }

    private function getItemValue(int $lineNo):string
    {
        $zabbixMethod   =   "Item.get";
        $zabbixParam    = '{"output":["lastclock","lastns","lastvalue","prevvalue"],"itemids":"'.$lineNo.'","sortfield":"name"}';
        $zabbixParam = json_decode($zabbixParam, true);
        $zabbixResult = $this->zabbixRequest($zabbixMethod, $zabbixParam);

        if(isset($zabbixResult['result'][0]['lastvalue'])) {
            return $zabbixResult['result'][0]['lastvalue'];
        } else {
            return "N/A";
        }
    }

    private function formatGroup(array $groupInfo): string
    {
        $output = "{$groupInfo['name']}：{$groupInfo['trigger']}";
        return $output;
    }

    private function formatLineLatency(array $lineLatenyInfo): string
    {
        $latency = $lineLatenyInfo['latency'] * 1000;
        $output = "{$lineLatenyInfo['name']}：{$latency} ms";
        return $output;
    }

    private function formatLineTraffic(array $lineTrafficInfo): string
    {
        $speedIcon = "[----------]";
        $up = sprintf("%1.f" ,$lineTrafficInfo['up'] / 1048576);
        $down = sprintf("%1.f" ,$lineTrafficInfo['down'] / 1048576);
        $number = ceil( max($up, $down) * 10 / $lineTrafficInfo['speed']);
        $speedIcon = preg_replace("/-/", "|", $speedIcon, $number);
        $output ="{$lineTrafficInfo['name']}:{$speedIcon}\n";
        $output .= "{$up}/{$down}/{$lineTrafficInfo['speed']}(U/D/Max)";
        return $output;
    }

    private function formatTrigger(array $triggerInfo): string
    {
        $output = "【{$this->severityToStr($triggerInfo['priority'])}】".date("m/d H:i:s ", $triggerInfo['lastchange'])."{$triggerInfo['hostname']}：{$triggerInfo['description']}；已持续：".$this->secsToStr(time() - $triggerInfo['lastchange']);
        return $output;
    }

    private function buildWeOAOverviewMsg(array $groupInfo, array $lineLatencyInfo, array $lineTrafficInfo, array $triggerInfo): string
    {
        $output     = "=====================\n";
        $output .= "      Heimdall  \n";

        $output     .= "=====================\n";
        $output .=   date("M.dS (D) H:i", time())."\n";

        $output     .= "=====================\n";
        foreach ($groupInfo as $group) {
            $output .= $this->formatGroup($group)."\n";
        }

        $output     .= "=====================\n";
        foreach ($lineLatencyInfo as $lineLatency) {
            $output .= $this->formatLineLatency($lineLatency)."\n";
        }

        $output     .= "=====================\n";
        foreach ($lineTrafficInfo as $lineTraffic) {
            $output .= $this->formatLineTraffic($lineTraffic)."\n";
        }

        if (sizeof($triggerInfo) > 0) {
            $output     .= "=====================\n";
            foreach ($triggerInfo as $trigger) {
                $output .= $this->formatTrigger($trigger)."\n";
            }
        }
        return $output;
    }

    private function loadOverviewInput()    // todo: 这里先用静态的，以后改动态的
    {
        $this->monitorGroup = array(
            array('name' => "上数", 'id' => 21),
            array('name' => "亦庄", 'id' => 18),
            array('name' => "广场", 'id' => 20),
            array('name' => "公网", 'id' => 22),
            array('name' => "HTTP", 'id' => 19),
            array('name' => "网络", 'id' => 16),
        );
        $this->netLineLatency = array(
            array('name' => "金融街专线", 'id' => 28231),
            array('name' => "亦庄专线", 'id' => 28288),
            array('name' => "上数专线", 'id' => 28991),
        );
        $this->netLineTraffic = array(
            array('name' => '广场互联网', 'upId' => 29870, 'downId' => 29843, 'speed' => 40),
            array('name' => '中心互联网', 'upId' => 29951, 'downId' => 29924, 'speed' => 60),
        );
    }

    public function buildWeOAOverview():string
    {
        $this->loadOverviewInput();

        $groupInfo  =   array();
        $lineLatencyInfo   =   array();
        $lineTrafficInfo   =   array();

        foreach($this->monitorGroup as $group)
        {
            $groupInfo[] = array('name' => $group['name'], 'trigger' => $this->getGroupTrigger($group['id']));
        }

        foreach ($this->netLineLatency as $lineLatency) {
            $lineLatencyInfo[] = array('name' => $lineLatency['name'], 'latency' => $this->getItemValue($lineLatency['id']));
        }

        foreach ($this->netLineTraffic as $lineTraffic) {
            $lineTrafficInfo[] = array('name'   => $lineTraffic['name'],
                                       'up'     => $this->getItemValue($lineTraffic['upId']),
                                       'down'   => $this->getItemValue($lineTraffic['downId']),
                                       'speed'  => $lineTraffic['speed']);
        }

        $triggerInfo    =   $this->getAllTriggers(); // todo:获取所有trigger；后续加上group和host

        $sendMessage    =   $this->buildWeOAOverviewMsg($groupInfo, $lineLatencyInfo, $lineTrafficInfo, $triggerInfo);

        return $sendMessage;

    }
}